import { Box, Divider, Text, VerticalStack } from '@shopify/polaris'
import React, { useEffect, useState } from 'react'
import GithubSimpleTable from '../../../components/tables/GithubSimpleTable'
import Category from './Category'
import { CellType } from '../../../components/tables/rows/GithubRow'

const aktoFindingsTableResourceName = {
    singular: 'Akto finding',
    plural: 'Akto findings',
}

const ReportFindings = ({ aktoFindingsTableData, categoryVsIssuesMap, organizationName, subCategoryMap }) => {
    const [aktoFindingsTableHeaders, setAktoFindingsTableHeaders] = useState([
        {
            title: "S.No.",
            value: "sno",
            type: CellType.TEXT,
            boxWidth: '15px'
        },
        {
            title: "Issue",
            value: "issueNameComp",
            textValue: "issueName",
            boxWidth: '100px'
        },
        {
            title: "Issue description",
            value: "issueDescriptionComp",
            textValue: "issueDescription",
            boxWidth: '200px'
        },
        {
            title: "APIs affcted",
            value: "apisAffected",
            type: CellType.TEXT,
            boxWidth: '15px'
        },
        {
            title: "Issue Category",
            value: "issueCategoryComp",
            textValue: "issueCategory",
            boxWidth: '80px'
        },
        {
            title: "Impact",
            value: "issueImpactComp",
            textValue: "issueImpact",
            type: CellType.TEXT,
        }
    ])

    let issueNo = 0
    const [totalIssues, setTotalIssues] = useState(0)

    useEffect(() => {
        const mediaQueryList = window.matchMedia('print')

        const handlePrint = (e) => {
            if (e.matches) {
                setAktoFindingsTableHeaders((prevHeaders) =>
                    prevHeaders.filter(header => header.value !== "issueCategoryComp")
                )
            } else {
                setAktoFindingsTableHeaders((prevHeaders) => {
                    if (prevHeaders.some(header => header.value === "issueCategoryComp")) {
                        return prevHeaders
                    }
                    const index = 4
                    const newHeaders = [...prevHeaders]
                    newHeaders.splice(index, 0, {
                        title: "Issue Category",
                        value: "issueCategoryComp",
                        textValue: "issueCategory",
                        boxWidth: '80px'
                    });
                    return newHeaders
                })
            }
        }

        mediaQueryList.addEventListener('change', handlePrint)
        return () => mediaQueryList.removeEventListener('change', handlePrint)
    }, [])

    const setCountApis = (aktoFindingsTableData) => {
        let countApis = 0
        aktoFindingsTableData.forEach(item => {
            countApis += item.apisAffected
        })
        setTotalIssues(countApis)
    }

    useEffect(() => {
        setCountApis(aktoFindingsTableData)
    }, [aktoFindingsTableData])


    return (
        <Box id="findings-table" paddingBlockStart={6} paddingBlockEnd={6} paddingInlineStart={5} paddingInlineEnd={5}>
            <VerticalStack gap="4">
                <Text variant="headingLg">2. Akto findings for <span id='organization-name'>{organizationName}</span></Text>
                <VerticalStack gap="3">
                    <Text variant="bodyMd" color='subdued'>
                        The security assessment of <span id='organization-name'>{organizationName}</span> revealed several significant vulnerabilities across different security categories. Each identified vulnerability has been thoroughly analyzed to understand its potential impact on the application's security.
                    </Text>
                    <GithubSimpleTable
                        key="table"
                        data={aktoFindingsTableData}
                        resourceName={aktoFindingsTableResourceName}
                        headers={aktoFindingsTableHeaders}
                        useNewRow={true}
                        condensedHeight={true}
                        hideQueryField={true}
                        headings={aktoFindingsTableHeaders}
                        hidePagination={true}
                        showFooter={false}
                    />

                    <Box paddingBlockStart={4}>
                        {
                            Object.keys(categoryVsIssuesMap).length > 0 && Object.keys(categoryVsIssuesMap).map((categoryName, index) => {
                                const issuesArr = categoryVsIssuesMap[categoryName]
                                return issuesArr.map((issue, issueIndex) => {
                                    return (
                                        <Box key={`${categoryName}-${issueIndex}`}>
                                            <Category
                                                key={issueNo}
                                                index={issueNo++}
                                                issue={issue}
                                                subCategoryMap={subCategoryMap}
                                                viewMode={totalIssues > 100 ? 'markdown' : 'syntax'}
                                            />
                                            {index !== Object.keys(categoryVsIssuesMap).length - 1 || issueIndex !== issuesArr.length - 1 ? <Box paddingBlockStart={4} paddingBlockEnd={4}><Divider /></Box> : null}
                                        </Box>
                                    )
                                })
                            })
                        }
                    </Box>
                </VerticalStack>
            </VerticalStack>
        </Box>
    )
}

export default ReportFindings